import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:xiang/utils/eventBus.dart';
import 'package:xiang/utils/http.dart';
import 'package:xiang/utils/toast.dart';

class ProfilePage extends StatefulWidget {
  ProfilePage({super.key, required this.userInfo});

  Map userInfo = {"id": "", "avatar": null, "nickName": null};

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  //接收
  Map userInfo = {};
  //昵称输入框控制器
  final TextEditingController _nickNameController = TextEditingController();

  //修改昵称
  void editNickName() async {
    String nickName = _nickNameController.text;
    if (!nickName.isNotEmpty) {
      return ToastUtil.showError('昵称不能为空');
    }
    if (nickName.length > 10) {
      return ToastUtil.showError('昵称不能超过10个字');
    }
    try {
      await http.put('/userInfo', {'nickName': nickName});
      ToastUtil.showSuccess('修改成功');
    } catch (e) {
      ToastUtil.showError(e.toString());
    }
  }

  //头像模态框
  void showBottomSheet() async {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
              height: 150,
              child: Column(children: [
                ListTile(
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  onTap: () {
                    uploadAvatar('camera');
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  onTap: () {
                    uploadAvatar('gallery');
                    // _pickImageFromGallery();
                  },
                )
              ]));
        });
  }

  //调用相机、相册获取图片
  uploadAvatar(String imageType) async {
    ImagePicker picker = ImagePicker();
    if (imageType == 'camera') {
      final XFile? photo = await picker.pickImage(source: ImageSource.camera);
      if (photo != null) {
        try {
          _pickImageFromGallery(photo);
        } finally {
          Navigator.pop(context);
        }
      }
    } else if (imageType == 'gallery') {
      final XFile? photo = await picker.pickImage(source: ImageSource.gallery);
      if (photo != null) {
        try {
          _pickImageFromGallery(photo);
        } finally {
          Navigator.pop(context);
        }
      }
    }
  }

  //上传图片
  Future<void> _pickImageFromGallery(XFile pickedFile) async {
    try {
      FormData formData = FormData.fromMap({
        "file": await MultipartFile.fromFile(pickedFile.path),
        "type": "avatar",
      });
      var res = await http.post('/upload', formData);
      if (res['code'] != 10000) return ToastUtil.showError('上传图片失败!');
      setState(() {
        userInfo['avatar'] = res['data']['url'];
      });
    } finally {
      Navigator.pop(context);
      eventBus.fire(EditProfile());
    }
  }

  @override
  void initState() {
    super.initState();
    setState(() {
      userInfo = widget.userInfo;
      _nickNameController.text = userInfo['nickName'] ?? '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
          title: const Text('个人信息'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
          leading: IconButton(
              onPressed: () {
                eventBus.fire(EditProfile());
                Navigator.pop(context);
              },
              icon: const Icon(Icons.arrow_back_ios))),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text('头像', style: TextStyle(fontSize: 16)),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        showBottomSheet();
                      },
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(200.0),
                          child: userInfo['avatar'] == null
                              ? Image.asset('assets/images/avatar_1.jpg',
                                  width: 30, height: 30)
                              : Image.network(
                                  userInfo['avatar'],
                                )),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
          Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                      hintText: '请输入昵称', border: InputBorder.none),
                  textAlign: TextAlign.right,
                  onEditingComplete: () {
                    editNickName();
                  },
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          )
        ],
      ),
    );
  }
}
